package com.parking.mgr.useraccount.interceptor;

import com.parking.mgr.common.annotion.LoginAuth;
import com.parking.mgr.common.exception.LoginAuthException;
import com.parking.mgr.common.exception.enums.AuthExceptionEnum;
import com.parking.mgr.useraccount.facede.LoginServiceFacede;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @ClassName LoginAuthInterceptor
 * @Description TODO
 * @Auther: zhijianpu
 * @Date: 2023/6/12
 */
@Component
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Resource
    private LoginServiceFacede loginServiceFacede;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            final Class<?> clazz = handlerMethod.getBeanType();
            final Method method = handlerMethod.getMethod();

            // 判断LoginAuth注解是标记在所调用的方法上还是在其类上
            if (clazz.isAnnotationPresent(LoginAuth.class) || method.isAnnotationPresent(LoginAuth.class)) {
                boolean isLoginAuth = loginServiceFacede.isLoginAuth(request);
                if (!isLoginAuth) {
                    throw new LoginAuthException(AuthExceptionEnum.NO_LOGIN_USER.getMessage());
                }
            }
        }
        return true;
    }
}
